﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Net;
using System.Net.Mail;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Outlook = Microsoft.Office.Interop.Outlook;
using Word = Microsoft.Office.Interop.Word;
using Hardcodet.Wpf.TaskbarNotification;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Collections.ObjectModel;
using WpfApplication1.Models;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Bestilling_new.xaml
    /// </summary>
    public partial class Bestilling_new : Window
    {
        public Bestilling_new()
        {
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(Bestilling_new_Closing);
        }

        private void Bestilling_new_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }
                
        public void ShowStandardBalloon()
        {
            string title = "WPF NotifyIcon";
            string text = "This is a standard balloon";
            TaskbarIcon tb = (TaskbarIcon)this.FindResource("MyNotifyIcon");
            //show balloon with built-in icon
            tb.ShowBalloonTip(title, text, tb.Icon);
        }

        private void bestil_Click(object sender, RoutedEventArgs e)
        {
            if (Indiumradiobutton.IsChecked==true)
            {
                var newWindow = new Indium();
                newWindow.Show();
            }
            else if (DaTSCANradiobutton.IsChecked == true)
            {
                var newWindow = new DaTSCAN();
                newWindow.Show();
            }
            else if (Jodradiobutton.IsChecked == true)
            {
                var newWindow = new Jod();
                newWindow.Show();
            }
            else if (Adreviewradiobutton.IsChecked == true)
            {
                var newWindow = new Adreview();
                newWindow.Show();
            }
            else if (NorIodradiobutton.IsChecked == true)
            {
                var newWindow = new NorIod();
                newWindow.Show();
            }
            else
            {
                MessageBox.Show("Der er gået noget galt med din bestilling", "Fejl", MessageBoxButton.OK, MessageBoxImage.Hand);
            }
        }

        // Metode til indsættelse af xml (Forældet)
        public static void XMLquery(string produkt, int antal, string dato, int ordreNr, string bestiltAf)
        {
            XElement loadXML = XElement.Load("../../Data/employees.xml");
            
            XElement ordre = new XElement("Ordre", 
                //new XAttribute("Produkt", "Octreoscan"),
                new XElement("Produkt", produkt),
                new XElement("Antal", antal),
                new XElement("Dato", DateTime.Today.Date.ToString("dd-MM-yyyy")),
                new XElement("BestiltAf", bestiltAf),
                new XElement("TilLevering", dato),
                new XElement("OrdreNr", ordreNr));
            loadXML.Add(ordre);
            //loadXML.Save("K:/Ansattes mapper/Thomas/Data/employees.xml");
            loadXML.Save("../../Data/employees.xml");
        }

        public static void SendMail(string to, string produkt, int antal, string dato, int ordreNr, string bestiltAf)
        {
            string subject, body;

            try
            {
                // Create the Outlook application by using inline initialization.
                Outlook.Application oApp = new Outlook.Application();

                //Create the new message by using the simplest approach.
                Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

                //Add a recipient.
                // TODO: Change the following recipient where appropriate.
                Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(to);
                oRecip.Resolve();

                //Set the basic properties.
                if (produkt == "Indium")
                {
                    subject = "Bestilling Indium Oxin";
                    body = "Hej GE Healthcare\n\nNuklearmedicinsk afdeling, Aalborg Sygehus Syd vil gerne bestille følgende:\n\n" + antal + " stk. " + produkt + " til levering d. " + dato + " (ordrenr. " + ordreNr + ").\n\nVenlig hilsen\n\n" + bestiltAf + "\nNuklearmedicinsk afdeling\nAalborg Sygehus Syd";
                    oMsg.Subject = subject;
                    oMsg.Body = body;
                }
                else if (produkt == "DaTSCAN")
                {
                    subject = "Bestilling DaTSCAN-kit";
                    body = "Hej GE Healthcare\n\nNuklearmedicinsk afdeling, Aalborg Sygehus Syd vil gerne bestille følgende:\n\n"+ antal +" stk. "+ produkt +" til levering d. "+ dato +" (ordrenr. "+ ordreNr +").\n\nVenlig hilsen\n\n"+ bestiltAf +"\nNuklearmedicinsk afdeling\nAalborg Sygehus Syd";
                    oMsg.Subject = subject;
                    oMsg.Body = body;
                }
                else if (produkt == "Jod")
                {
                    subject = "Bestilling Jod";
                    body = "Hej GE Healthcare\n\nNuklearmedicinsk afdeling, Aalborg Sygehus Syd vil gerne bestille jod-kapsler (se vedhæftede fil).\n\nVenlig hilsen\n\n" + bestiltAf + "\nNuklearmedicinsk afdeling\nAalborg Sygehus Syd";
                    oMsg.Subject = subject;
                    oMsg.Body = body;                    
                }
                else if (produkt == "Adreview")
                {
                    subject = "Bestilling Adreview";
                    body = "Hej GE Healthcare\n\nNuklearmedicinsk afdeling, Aalborg Sygehus Syd vil gerne bestille følgende:\n\n" + antal + " stk. " + produkt + " til levering d. " + dato + " (ordrenr. " + ordreNr + ").\n\nVenlig hilsen\n\n" + bestiltAf + "\nNuklearmedicinsk afdeling\nAalborg Sygehus Syd";
                    oMsg.Subject = subject;
                    oMsg.Body = body; 
                }
                else if (produkt == "Nor-iod")
                {
                    subject = "Bestilling Nor-iod-cholesterol";
                    body = "Hej GE Healthcare\n\nNuklearmedicinsk afdeling, Aalborg Sygehus Syd vil gerne bestille følgende:\n\n" + antal + " stk. " + produkt + " til levering d. " + dato + " (ordrenr. " + ordreNr + ").\n\nVenlig hilsen\n\n" + bestiltAf + "\nNuklearmedicinsk afdeling\nAalborg Sygehus Syd";
                    oMsg.Subject = subject;
                    oMsg.Body = body; 
                }
                else
                {
                    MessageBox.Show("Der er gået noget galt med din bestilling", "Fejl", MessageBoxButton.OK, MessageBoxImage.Hand);
                }
                //Add an attachment.
                // TODO: change file path where appropriate
                String sSource = @"C:\Documents and Settings\tw6p\Skrivebord\Bestilling GE.doc";
                String sDisplayName = "Bestilling";
                int iPosition = (int)oMsg.Body.Length + 1;
                int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
                oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);

                // If you want to, display the message.
                // oMsg.Display(true);  //modal

                //Send the message.
                oMsg.Save();
                oMsg.Send();

                //Explicitly release objects.
                oRecip = null;
                oMsg = null;
                oApp = null;
            }

            // Simple error handler.
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                // Console.WriteLine("{0} Exception caught: ", e);
            }
        }

        public void EditDocument()
        {
            // declare objects and variables
            object fileName = Properties.Settings.Default.OrdreDokument;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            // create instance of Word
            Word.Application oWordApp = new Word.Application();

            // create instance of Word document
            Word.Document oWordDoc = new Word.Document();

            // open word document
            oWordDoc = oWordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref readOnly,
            ref missing, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing);

            oWordDoc.Activate();

            // debug to see that I can write to the document
            oWordApp.Selection.TypeText("This is the text that was written from the C# program! ");
            oWordApp.Selection.TypeParagraph(); //Note  This method corresponds to the functionality of the ENTER key.

            // Example of writing to bookmarks each bookmark will have exists around it to avoid null
            if (oWordDoc.Bookmarks.Exists("vendorName"))
            {
                // set value for bookmarks           
                object oBookMark = "vendorName";
                oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "Genesis Software Development";

                oBookMark = "vendorAddress";
                oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "3333 West 3rd Street";

                oBookMark = "vendorCity";
                oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "Austin";

                oBookMark = "vendorState";
                oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "TX";

                oBookMark = "vendorZip";
                oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "75235";

            }

            // save the document
            //oWordApp.Documents.Save(ref missing, ref missing);
            oWordDoc.SaveAs("c:\\test1.doc");

            // close the application            
            oWordApp.Application.Quit(ref missing, ref missing, ref missing);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //ShowStandardBalloon();

            Ordre test = new Ordre();
            test.BestiltAf = "John";

            OrdreItem item = new OrdreItem("ER23", "Endnu et test produkt", new DateTime(2012, 05, 08), new DateTime(2012, 05, 07), 4);
            List<OrdreItem> items = new List<OrdreItem>();
            items.Add(item);
            //OrdreItem[] array = new OrdreItem[15];
            //array.SetValue(item,0);            
            test.OrdreItem = items;
            test.addItem(item);

            test.insertOrdre(test, Properties.Settings.Default.OrdreDokument);

            //String xml = test.ordreToXml(test);
            //MessageBox.Show(test.Ordredato.ToShortDateString());
            //MessageBox.Show(xml);
            //Ordre test = new Ordre(DateTime.Now, 561978, "Thomas Schmidt", items);
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //OrdreCollection o = new OrdreCollection();
            // Indlæs elementerne fra den globale collection OrdreList
            OrdreCollection o = (OrdreCollection)this.FindResource("OrdreList");
            //ListView listview = (ListView)this.FindResource("ProduktListview");

            foreach(ListViewItem item in ProduktListview.Items)
            {
                MessageBox.Show(item.ToString());
            }
            // Opret et par ordreitems
            //OrdreItem item1 = new OrdreItem("Test3", "Endnu et test produkt", new DateTime(2012, 07, 08), new DateTime(2012, 07, 09), 4);
            //OrdreItem item2 = new OrdreItem("Test4", "Endnu et test produkt", new DateTime(2012, 10, 08), new DateTime(2012, 10, 08), 4);
            //OrdreItem item3 = new OrdreItem("Test5", "Endnu et test produkt", new DateTime(2012, 08, 24), new DateTime(2012, 08, 26), 4);
            //// Opret liste til at holde disse items
            //List<OrdreItem> items = new List<OrdreItem>();

            //// Tilføj ordreitems til listen
            //items.Add(item1);
            //items.Add(item2);
            //items.Add(item3);

            //// Opret ny ordre
            //Ordre test = new Ordre();
            //// Sæt variabel
            //test.BestiltAf = "Hans";
            //// Tilføj listen med ordreItems
            //test.OrdreItem = items;

            //// Tilføj Ordren til den globale ordreliste
            //o.OrdreList.Add(test);

            //// Gem den globale ordreliste som XML
            //o.createXmlFromCollection(o, Properties.Settings.Default.OrdreDokument);
                                    
            // Udskriv til skærmen et par elementer fra den globale ordreliste, som tjek at listen er opdateret med ny ordre
            foreach (var c in o.OrdreList)
            {
                MessageBox.Show(c.Ordredato.ToString());
            }


            // Test: Udskriv kun ordrer med leveringsdato efter dags dato
            //var query = from p in o.OrdreList
            // where p.OrdreItem. < DateTime.Now
            // select p;

            //foreach (var d in query)
            //{
            //    MessageBox.Show(d.Ordrereference.ToString());                
            //}
            //MessageBox.Show(o.ToString());

            //XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Ordre>));
            //using (StreamReader rd = new StreamReader("Data/Ordrer.xml"))
            //{
            //    o.OrdreList = xs.Deserialize(rd) as ObservableCollection<Ordre>;
            //}

            //foreach(
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            OrdreCollection o = (OrdreCollection)this.FindResource("OrdreList");
            //o.fillCollectionFromXml(Properties.Settings.Default.OrdreDokument);

            foreach (var c in o.OrdreList)
            {
                MessageBox.Show(c.Ordredato.ToString());
            }

            var query = from p in o.OrdreList
                        where p.Ordredato < DateTime.Now
                        select p;

            foreach (var d in query)
            {
                MessageBox.Show(d.Ordrereference.ToString());
            }

            o = null;
            query = null;

            //OrdreCollection o = new OrdreCollection();
            //o.fillCollectionFromXml(Properties.Settings.Default.OrdreDokument);
            //this.Resources.Add("OrdreList", o);
        }
    }
}